{-#LANGUAGE TemplateHaskell,DeriveGeneric,FlexibleInstances,QuasiQuotes,OverloadedStrings,RecordWildCards#-}
module App.Article.DB (module App.Article.TH.DB,dbArticle2S,dbArticle2D,SimpleArticle(..),DetailArticle(..)) where
import Data.Int
import App.Article.TH.DB
import Data.Aeson
import qualified Data.Text as T
import GHC.Generics
import Data.Time
import Data.Time.Format
import Data.Time.LocalTime

data SimpleArticle = SimpleArticle {
    id::Int64,
    title::T.Text,
    context::T.Text,
    createTime::T.Text
} deriving (Generic)

instance ToJSON SimpleArticle

data DetailArticle = DetailArticle {
  dId::Int64,
  dTitle::T.Text,
  dContext::T.Text,
  dCreateTime::T.Text
} deriving (Generic)

instance ToJSON DetailArticle
instance ToJSON Article

convTime zone time = formatTime defaultTimeLocale "%Y-%m-%d-%H-%M" (utcToLocalTime zone  time)

dbArticle2S::(Int64,Article) -> IO SimpleArticle
dbArticle2S (aid,a@Article{..}) = do
    timeZone <-  getCurrentTimeZone
    let timeStr = convTime timeZone articleCreateTime
    return $ SimpleArticle {
     id = aid,
     title = articleTitle,
     context = T.take 100 articleContext,
     createTime = T.pack timeStr}

dbArticle2D::(Int64,Article) -> IO DetailArticle
dbArticle2D (aid,a@Article{..}) = do
    timeZone <-  getCurrentTimeZone
    let timeStr = convTime timeZone articleCreateTime
    return $ DetailArticle {
     dId = aid,
     dTitle = articleTitle,
     dContext = articleContext,
     dCreateTime = T.pack timeStr
    }